<?php
class Download {
	protected $fileType;
	protected $fileSize;
	protected $fileUrl;
	protected $savedDir = "downloads";
	protected $savedFileName;
	public $errors = array();
	protected $message;
	protected $filetestflag =0;
	public $savedfilepath;
	
	public function __construct(){
		$this->fileType[] = "*";//default can download all files;
		$this->fileSize = "*";//not used for now ;
		
	}
	
	public function setFileType($type,$add=true){
		if (!$add){
			$this->fileType = "";
		}
		if (is_array($type)&&!empty($type)){
			foreach($type as $value){
				$this->fileType[] = $value;
			}
		}else {
			$this->fileType[] = $type;
		}
	}
	
	public function setFileSize($size){
		$this->size = (float)$size;
	}
	
	public function setFileUrl($url){
		$this->fileUrl = $url;
	}
	
	public function getDefaultFileName(){
		if (strrchr($this->fileUrl,"/")){
			$url = explode("/",$this->fileUrl);
		}else {
			$url = explode("\\",$this->fileUrl);
		}
		$len = count($url)-1;
		$name = $url[$len];
		return $name;
	}
	
	public function getFileTypes(){
		return $this->fileType;
	}
	
	public function getFileSize(){
		return $this->fileSize;
	}
	public function setError($error){
		$this->errors[] = $error;
	}
	public function getErrors(){
		return $this->errors;
	}
	
	public function getMessage(){
		return $this->message;
	}

	public function filetest($filepath){
		if(file_exists($filepath)){	
			$this->filetestflag +=1;
			$filearr = explode(".",$filepath);
			$count = count($filearr);
			$last = $count-1;
			$temarr=array();
			for ($i=0;$i<$last;$i++){
				$temarr[] = $filearr[$i];
			}
			$fileprex = implode("/",$temarr);
			
			if (strrchr($fileprex,"(")){
				$fileprexarr = explode("(",$fileprex);
				$fileprex = $fileprexarr[0];
			}
			$filepath = $fileprex."(".$this->filetestflag.")".".".$filearr[$last];
			$this->filetest($filepath);
		}else {
			//echo $filepath." last <br />";
			$this->savedfilepath = $filepath;
			return $filepath;
		}
	}
	
	//match the img src, return src array
	public function getImages($imgstring){
		$imgstring = stripslashes($imgstring);
		$imgstring = str_replace("&amp;","&",$imgstring);
		$img_array = array();
		//preg_match_all("/(src|SRC)=[\"|'| ]{0,}(http:\/\/(.*)\.(gif|jpg|jpeg|bmp|png))/isU",$imgstring,$img_array);
		//preg_match_all("/(src|SRC)=[\"|'| ]{0,}(http:\/\/(.*)(\.)?[^\s])[\"|'| ]/isU",$imgstring,$img_array);
		preg_match_all("/(src|SRC)=[\"|'| ]{0,}(http:\/\/(.*))[\"|'| ]/isU",$imgstring,$img_array);
		$img_array = array_unique($img_array[2]);
		//var_dump($img_array);
		//$img_array=array();
		//$img_array = $img_array[2];
		return $img_array;	
	}
	/**
	 * multy download imgages from $imgstring
	 *
	 * @param unknown_type $imgstring
	 * @param unknown_type $filename
	 * @return unknown
	 */
	public function download($imgstring,$filename){
		$Log = new Log();
		$imgarr = $this->getImages($imgstring);
		/*if (empty($imgarr)){
			$this->setError("images are not matched");
			$Log = new Log();
			$Log->write("download images :images are not matched");
		}*/
		$imgstringNew=$imgstring;
		if(!empty($imgarr)){
			foreach ($imgarr as $img){
				$savedPath = $this->doDownloadFiles($img,$filename);
				//$imgstring = ereg_replace($img,$savedPath,$imgstring);
				$img=str_replace('&','&amp;',$img);
				$imgstringNew = str_replace($img,$savedPath,$imgstringNew);
				//$imgstring = str_replace($img,$savedPath,$imgstring);
			}
		}
		return $imgstringNew;
		
	}
	
	/**
	 * Enter description here...
	 *
	 * @param string $fileUrl;
	 * @param string $filename saved file name;
	 * @return unknown
	 */
	public function doDownloadFiles($fileUrl,$filename=""){
		$Log = new Log();
/*		$Log->write("saved images iterm start:".$filename);*/
		$this->setFileUrl($fileUrl);
		$type = substr(strrchr($fileUrl,"."),1);
		if (!in_array($type,$this->fileType)&&!in_array("*",$this->fileType)){
			$this->errors[] = "file type not allowed.";
			/*$Log->write("download images:file type not allowed.");*/
			return $this;
		}
		$directory = $this->savedDir;
		if (!is_dir($directory)){
					mkdir($directory);
		}
		if(!$filename){
			$filename = $directory."/".$this->getDefaultFileName();
		}else{
			if (strrchr($filename,"/")){
				$lasttemp ="";
				$dirs = explode("/",$filename);
				
				
				$dircount = count($dirs);
				
				if (strrchr($filename,"/")=="/"){
					$lasttemp = $this->getDefaultFileName();
					
				}else{
					$dircount = $dircount-1;
					$lasttemp = "/".$dirs[$dircount];
				}
		
				for($i=0;$i<$dircount;$i++){
					$dir = $dirs[$i];
					if (!is_dir($directory."/".$dir)){
						mkdir($directory."/".$dir);	
					}
					
					$directory.= "/".$dir;
					
				}
				/////////////add user id 
				$userId='';
				if (isset($_SESSION)&&$_SESSION['userId']){
					$userId=$_SESSION['userId'];
				}else{
					@session_start();
					if (isset($_SESSION['userId'])){
						$userId=$_SESSION['userId'];
					}
				}
				if (!$userId){
					$filename = $directory.$lasttemp;
				}else{
					if (!is_dir($directory.$userId))
						mkdir($directory.$userId);
					$filename = $directory.$userId."/".$lasttemp;
				}
				
				/////
				/*$filename = $directory.$lasttemp;*/
			}
		}
/*		$Log->write("saved images iterm process:".$filename);*/
		//check if the file is exsit in the download folder;
		$filename = $this->filetest($filename);
		if (!$filename){
			$filename = $this->savedfilepath;
		}
		
		$filename = str_replace("=","",$filename);
		$filename = str_replace("&","",$filename);
		$finamearr = explode(".",$filename);
		$length = count($finamearr)-1;
		$extence = $finamearr[$length];
		$filetypesArr= array("jpg","png","gif","jpeg","bmp"); 
		if(!in_array($extence,$filetypesArr)){
			$filename = $filename.".jpg";
		}
		if (stripos($filename,'?')!==false)
			$filename=str_replace('?','',$filename);
		$imgPath=array();
		$imgPath = explode("/",$filename);
		$lenPath = (count($imgPath))-1;
		$lastName= $imgPath[$lenPath];
		$dotArray =array();
		$dotArray=explode(".",$lastName);
		$dotlen =count($dotArray)-1;
		$lastExt=$dotArray[$dotlen];
		$lastName=str_replace(".".$lastExt,"",$lastName);
		$lastName=str_replace(".","",$lastName);
		$lastName=$lastName.".".$lastExt;
		$newFilename='';
		foreach ($imgPath as $key=>$slipPa){
			if ($newFilename&&$key!=$lenPath){
				$newFilename.="/".$slipPa;
			}else if($key!=$lenPath&&$newFilename==''){ 
				$newFilename=$slipPa;
			}
		}
		$filename=$newFilename."/".$lastName;
		ob_start();
	    readfile($fileUrl);
	    $img = ob_get_contents();
	    ob_end_clean();
	    $fp = fopen($filename, 'a') ;
	    if ($fp){
	    	fwrite($fp,$img);
	    	fclose($fp);
	    	$this->message["log"][] = "success download file from $fileUrl;<br />saved at : $filename";
	    	$this->message["url"][] = $filename;
	    }else{
	    	$this->errors[] = "failed open file ".$filename;
	    	$Log = new Log();
			$Log->write("download images:failed open file ".$filename);
	    }
	    $this->message["errors"] = $this->errors;
	    return $filename;
	}
	
}
?>